package packageParser;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.Map;

import packageHandler.PackageHandlerForServer;
import protocol.DataPackage;
import protocol.JsonPackage;
import util.DBUtil;

//这里可以取出来一个PackageHandler
public class PackageParserForServer {
	public static boolean packageParse(Map<String, BufferedWriter> socketList, List<String> userList, DataPackage pack){
		
		DataPackage.MessageType type = pack.getMessageType();
		
		//判断用户发送过来的message类型，并根据不同的类型，服务器做出相应的动作
		
		//转发package
		if(type == DataPackage.MessageType.MESSAGE || type == DataPackage.MessageType.SHAKE){
			PackageHandlerForServer.transmitMassageForClient(socketList, userList, pack);
		}
		//通知所有用户有一个用户下线
		else if (type == DataPackage.MessageType.LOGOUT){
			if(pack.getFromName().equals("//")){
				System.out.println("log out from superl.......................");
				DataPackage shutDownPackage = new DataPackage("//", "\\", DataPackage.MessageType.LOGOUT, "", 0);
				for(String i:userList){
					BufferedWriter out = socketList.get(i);
					try {
						out.write(new JsonPackage(shutDownPackage).getJsonString() + "\n");
						out.flush();
					} catch (IOException e) {
						System.out.println("用户下线，服务端向所有用户发送用户列表失败");
						e.printStackTrace();
					}
				}
				System.out.println("执行完了超级用户的下线通知");
				return true;
			}
			else if(pack.getFromName().equals("////")){
				return false;
			}
			
			DBUtil.logout(pack.getFromName());
			PackageHandlerForServer.clientLogout(socketList, userList, pack);
			return false;
		}
		return true;
	}
}
